package com.ruoyi.system.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


import com.ruoyi.system.domain.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.MealVerification;
import com.ruoyi.system.domain.VerificationVO;
import com.ruoyi.system.domain.dto.MealVerificationQueryDTO;
import com.ruoyi.system.domain.vo.MealVerificationResultVO;
import com.ruoyi.system.service.IMealVerificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

/**
 * 核销管理Controller
 * 
 * @author ruoyi
 * @date 2025-08-15
 */
@RestController
@RequestMapping("/verification/verification")
public class MealVerificationController extends BaseController
{
    @Autowired
    private IMealVerificationService mealVerificationService;

    /**
     * 查询核销管理列表
     */
    @PreAuthorize("@ss.hasPermi('verification:verification:list')")
    @GetMapping("/list")
    public TableDataInfo list(MealVerification mealVerification)
    {
        startPage();
        List<MealVerification> list = mealVerificationService.selectMealVerificationList(mealVerification);
        return getDataTable(list);
    }

    /**
     * 查询核销管理VO列表（包含订餐信息）
     */
    @PreAuthorize("@ss.hasPermi('verification:verification:list')")
    @GetMapping("/voList")
    public TableDataInfo voList(VerificationVO verificationVO)
    {
        startPage();
        List<VerificationVO> list = mealVerificationService.selectVerificationVOList(verificationVO);
        return getDataTable(list);
    }
    /**
     * 导出核销管理列表
     */
    @PreAuthorize("@ss.hasPermi('verification:verification:export')")
    @Log(title = "核销管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public void export(HttpServletResponse response, MealVerification mealVerification)
    {
        List<MealVerification> list = mealVerificationService.selectMealVerificationList(mealVerification);
        ExcelUtil<MealVerification> util = new ExcelUtil<MealVerification>(MealVerification.class);
        util.exportExcel(response, list, "核销管理数据");
    }

    @PreAuthorize("@ss.hasPermi('verification:verification:export')")
    @Log(title = "核销管理", businessType = BusinessType.EXPORT)
    @PostMapping("/exportVo")
    public void exportVo(HttpServletResponse response, VerificationVO verificationVO)
    {
        List<VerificationVO> list;
        if (verificationVO.getIds() != null && !verificationVO.getIds().isEmpty()) {
            // 如果提供了ID列表，则根据ID列表查询
            String[] idArray = verificationVO.getIds().split(",");
            List<Long> ids = new ArrayList<>();
            for (String id : idArray) {
                ids.add(Long.parseLong(id.trim()));
            }
            list = mealVerificationService.selectVerificationVoListByIds(ids);
        } else {
            // 否则使用常规查询
            list = mealVerificationService.selectVerificationVOList(verificationVO);
        }
        ExcelUtil<VerificationVO> util = new ExcelUtil<VerificationVO>(VerificationVO.class);
        util.exportExcel(response, list, "核销管理数据");
    }

    /**
     * 导出核销管理（按培训分组）
     */
    @PreAuthorize("@ss.hasPermi('verification:verification:export')")
    @Log(title = "核销管理", businessType = BusinessType.EXPORT)
    @PostMapping("/exportGrouped")
    public void exportGrouped(HttpServletResponse response, VerificationVO verificationVO) {
        System.out.println("=== 接收到导出请求 ===");
        System.out.println("请求参数: " + verificationVO);

        try {
            Map<String, List<VerificationExportVO>> groupedData = mealVerificationService.selectGroupedExportData(verificationVO);
            System.out.println("分组后的数据: " + groupedData);

            if (groupedData == null || groupedData.isEmpty()) {
                System.out.println("没有找到符合条件的核销数据");
                response.setContentType("text/plain;charset=UTF-8");
                response.getWriter().write("没有找到符合条件的核销数据");
                return;
            }

            VerificationExportUtil.exportGroupedExcel(response, groupedData, "核销管理数据.xlsx");
            System.out.println("导出完成");
        } catch (Exception e) {
            // 异常处理...
        }
    }

    /**
     * 获取核销管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('verification:verification:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(mealVerificationService.selectMealVerificationById(id));
    }

    /**
     * 新增核销管理
     */
    @PreAuthorize("@ss.hasPermi('verification:verification:add')")
    @Log(title = "核销管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MealVerification mealVerification)
    {
        return toAjax(mealVerificationService.insertMealVerification(mealVerification));
    }

    /**
     * 修改核销管理
     */
    @PreAuthorize("@ss.hasPermi('verification:verification:edit')")
    @Log(title = "核销管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MealVerification mealVerification)
    {
        return toAjax(mealVerificationService.updateMealVerification(mealVerification));
    }
    /**
     * 删除核销管理
     */
    @PreAuthorize("@ss.hasPermi('verification:verification:remove')")
    @Log(title = "核销管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(mealVerificationService.deleteMealVerificationByIds(ids));
    }
    /**
     * 根据员工ID和培训ID更新核销状态
     */
    @PreAuthorize("@ss.hasPermi('verification:verification:edit')")
    @Log(title = "核销管理", businessType = BusinessType.UPDATE)
    @PutMapping("/emp/{empId}/training/{trainingId}/status/{isVerified}")
    public AjaxResult updateVerificationStatusByEmpAndTraining(@PathVariable Long empId, @PathVariable Long trainingId, @PathVariable Integer isVerified)
    {
        return toAjax(mealVerificationService.updateVerificationStatusByEmpAndTraining(empId, trainingId, isVerified));
    }


    /**
     * 查询核销表，计算核销占比
     */
        @PostMapping("/query")
        public MealVerificationResultVO queryVerification(
                @Valid @RequestBody MealVerificationQueryDTO queryDTO) {
            return mealVerificationService.calculateVerification(queryDTO);
        }

}
